/**
 * Copyright (C), 2012-2018, 联奕科技有限公司
 * FileName: ShiguiwuAuthenticationFilureHandler
 * Author:   石贵武
 * Date:     2018\3\8 0008 19:02
 * Description: 失败登录的逻辑
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.zhoudongxiu.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhoudongxiu.security.core.enums.LoginType;
import com.zhoudongxiu.security.core.properties.SecurityProperties;
import com.zhoudongxiu.security.core.support.SimplResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 〈一句话功能简述〉<br> 
 * 〈失败登录的逻辑〉
 *
 * @author 石贵武
 * @create 2018\3\8 0008
 * @since 1.0.0
 */
@Component("shiguiwuAuthenticationFailureHandler")
@Slf4j
public class ShiguiwuAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler{

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.info("登录失败");
        if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(new SimplResponse(e.getMessage())));
        } else {
            super.onAuthenticationFailure(request, response, e);
        }
    }
}